// pages/splash/splash.js
var httpUtil = require('../../utils/httpUtil.js');
var uiUtil = require('../../utils/uiUtil.js');
var WXBizDataCrypt = require('../../utils/cryptoUtil.js');
const app = getApp();
const appId = 'wx2e65f1eb244a839b';
var that;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: null,//用户信息
    time:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this;

    var wxOfficialCodeOptions = wx.getStorageSync('wxOfficialCodeOptions');
    wxOfficialCodeOptions.wxOfficialCode = options.wxOfficialCode;
    options = wxOfficialCodeOptions;

    // 登录
    wx.login({
      success(res) {
        app.loginRequest(res.code,options.wxOfficialCode);
      }
    })

    that.timeout();

    // 登录code,用户信息
    if (app.globalData.loginStatus == 0) { //请求登录中
      app.loginRequestReadyCallback = res => {
        that.handlePageTo(options)
      }
    } else {
      that.handlePageTo(options)
    }
  },

  timeout(){
    setTimeout(function(){
      if(that.data.time<3){
        that.setData({
          time: that.data.time+1
        })
        that.timeout();
      }
    },1000)
  },

  handlePageTo(options) {

    // 启动页限时，最低3s
    if(that.data.time<3){
      setTimeout(function(){
        that.handlePageTo(options);
      },1000)
      return
    }

    var page = options.page
    if (app.globalData.loginStatus == 2) { //登录成功
      var url = '/pages/index/navigationbar/navigationbar'
      if(!page) { //正常进入首页
        url = '/pages/index/navigationbar/navigationbar'
      } else if (page == 'shop') { //商家首页
        var mchid = options.mchid;
        if (mchid) {
          url = '/pages/shop/shop/shop?mchId=' + mchid;
        }
      } else if (page == 'shop-details') { //商品详情
        var mchid = options.mchid
        var id = options.id
        if (id) {
          url = '/pages/shop/shop-details/shop-details?id=' + id + "&mchId=" + mchid;
        }
      }
      try {
        wx.redirectTo({
          url: url
        })
      } catch (e) {}
    } else { //登录失败
      
    }
  }
})